﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using System.Xml.Linq;
using System.Xml;

namespace EFong.View.Data
{
    public partial class Frm_DataExport : BasicForm
    {
        private BaseServiceProxy _proxy;

        public Frm_DataExport()
        {
            InitializeComponent();
        }

        protected override void InitFields()
        {
            base.InitFields();

            _proxy = BaseServiceProxy.GetInstance();
        }

        protected override void Events()
        {
            base.Events();

            this.btn_Cancel.Click += (s, e) =>
            {
                this.Close();
            };
            this.btn_Select.Click += (s, e) =>
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "XML文件(*.xml)|*.xml";
                saveFileDialog.FileName = string.Format("系统更新文件 {0}.xml", this.dte_ExportDate.DateTime.ToString("yyyy-MM-dd"));
                DialogResult result = saveFileDialog.ShowDialog();
                if (result != DialogResult.OK)
                    return;

                FileName = saveFileDialog.FileName;
                txt_Path.SetText(FileName);
            };
            this.btn_Export.Click += (s, e) =>
            {
                UIOperManager.SaveData(() => { return true; },
                    () =>
                    {
                        DateTime dateTime = dte_ExportDate.GetValue().Value;
                        dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
                        Contract.ServiceResult<XElement> result = _proxy.ExportData(dateTime);

                        if (result.IsSuccess)
                        {
                            using (StreamWriter outfile = new StreamWriter(FileName))
                            {
                                outfile.Write(result.ReturnValue.ToString());
                            }

                        }

                        return result.IsSuccess;
                    },
                    "导出成功.",
                    () =>
                    {
                        this.Close();
                    });
            };
        }

        protected override void LoadDatas()
        {
            base.LoadDatas();

            dte_ExportDate.SetValue(_proxy.GetLatestExportDate().ReturnValue);
        }

        public string FileName { get; set; }
    }
}
